<!DOCTYPE HTML>
<html>

<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
        content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <title>文件文件夹拖拽上传</title>
    <style>
        .dragarea {
            width: 100%;
            height: 150px;
            box-sizing: border-box;
            border: 1px dashed rgb(27, 27, 189);
            text-align: center;
            border-radius: 8px;
        }

        .dragarea span {
            line-height: 150px;
            color: #5f5a5a;
            cursor: pointer;
        }


        .dropcontext {
            position: relative;
            margin-top: 30px;
            width: 100%;
            height: 300px;
            overflow: auto;
            background-color: #e1e1e1;
            border-radius: 8px;
            padding: 10px;
            box-sizing: border-box;
        }

        .dropcontext ul {
            list-style-type: none;
        }

        .dropcontext li:after {
            clear: both;
        }

        .dropcontext ul:after {
            clear: both;
        }

        .dropcontext .need {
            color: rgb(25, 0, 253);
        }

        .dropcontext .update {
            color: #8f3a3a;
        }

        .dropcontext .defect {
            color: #ff0000;
        }

        .dropcontext:after {
            clear: both;
        }

        .pageheader {
            position: relative;
            height: 100px;
            text-align: left;
            color: #575656;
            background-color: #e1e1e1;
            border-radius: 4px;
            margin-bottom: 20px;
            font-size: 12px;
        }

        .pageheader span {
            display: block;
            position: relative;
        }

        .page-container {
            position: relative;
            max-width: 700px;
            margin: auto;

        }

        .uploadbtn {
            height: 50px;
            line-height: 50px;
            outline: none;
            width: 100%;
            box-sizing: border-box;
            border-radius: 4px;
            margin-top: 20px;
            border: none;
            background-color: rgb(27, 114, 114);
            color: white;
            cursor: pointer;
        }

        .uploadbtn:hover {
            background-color: rgb(23, 173, 173);
        }

        .uploadbtn:disabled {
            background-color: #575656;
        }
    </style>
</head>

<body>
    <div class="page-container">

        <div class="pageheader">
            <span></span>
        </div>
        <div class="dragarea js-drag item">
            <span>请把文件拖动到这里来</span>
        </div>

        <div class="dropcontext">
            <ul>
            </ul>
        </div>

        <div class="divupload">
            <!-- <label>
                <input type="file" style="display: none;" multiple value="添加" onchange="funcselectfile(this);">
            </label> -->
        </div>

        <div class="btnarea">

            <input type="button" value="同步" onclick="btnupload();" class="uploadbtn" disabled>

        </div>
    </div>


    <script type="text/javascript" src="../lib/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="../lib/layer/2.4/layer.js"></script>
    <script src="../lib/api.js"></script>
    <script type="text/javascript">

        var sid = 0;
        var modelid = 2;
        var mapconfig = new Map();
        var mapremote = new Map();

        $(window).ready(function () {
            var pidstr = _apigetquery("id");
            if (pidstr != null) {
                sid = parseInt(pidstr);
            }
            var modelstr = _apigetquery("mid");
            if (modelstr != null) {
                modelid = parseInt(modelstr);
            }

            _apiget("/api/spider/upload/config?serviceid=" + sid + "&model=" + modelid, true, function (code, obj) {
                if (code == 200) {
                    if (obj.length > 0) {
                        for (var k = 0; k < obj.length; k++) {
                            var item = obj[k];
                            if (!mapconfig.has(item.fileName)) {
                                mapconfig.set(item.fileName, item);
                            }
                        }
                    }
                    _appendmessage("读取文件配置完成!");
                }
            });
            _apiget("/api/spider/upload/read?serviceid=" + sid + "&model=" + modelid, true, function (code, obj) {
                if (code == 200) {
                    if (obj.length > 0) {
                        for (var k = 0; k < obj.length; k++) {
                            var item = obj[k];
                            if (!mapremote.has(item.fullPath)) {
                                mapremote.set(item.fullPath, item);
                            }
                        }
                    }
                    _appendmessage("读取服务器文件完成！");
                }
            });
        });


        function readDirectory(directory) {
            return new Promise((resolve, reject) => {
                const dirReader = directory.createReader();
                let entries = [];
                const getEntries = function () {
                    dirReader.readEntries(
                        function (results) {
                            if (results.length) {
                                entries = entries.concat(results);
                                getEntries();
                            } else {
                                resolve(entries);
                            }
                        },
                        function (error) {
                            reject(error);
                        }
                    );
                };
                getEntries();
            });
        }

        async function readRoll(arr) {
            for (let key in arr) {
                if (arr[key].isDirectory) {
                    let result = await readDirectory(arr[key]);
                    arr[key] = result;
                    await readRoll(result);
                }
            }
        }

        function readFileEntry(fileEntry) {
            return new Promise((resolve, reject) => {
                fileEntry.file(
                    (fileData) => {
                        fileData.fullPath = fileEntry.fullPath;
                        resolve(fileData);
                    },
                    (error) => {
                        reject(error);
                    }
                );
            });
        }

        //export
        async function dropedFileReader(event) {
            if (!event.dataTransfer || !event.dataTransfer.items) {
                this.uploadLoading = false;
                throw new Error();
            }
            let fileEntryList = [];
            for (let item of event.dataTransfer.items) {
                fileEntryList.push(item.webkitGetAsEntry());
            }
            await readRoll(fileEntryList);
            fileEntryList = fileEntryList.flat(Infinity);
            const fileList = [];
            for (let item of fileEntryList) {
                let fileData = await readFileEntry(item);
                fileList.push(fileData);
            }
            return fileList;
        }


        //待上传的文件列表
        var _selectfilelist = null;
        //加载的时候注册事件
        window.onload = function () {

            var dragElement = document.querySelector('.js-drag');
            //过滤文件格式
            var fileTypeArray = ['exe', 'pbo', 'less'];
            var file = {
                type: function (files, fileTypeArray) {
                    //这里做文件的过滤
                    if (_selectfilelist == null) { _selectfilelist = []; }
                    _selectfilelist.push(files);
                },
                info: function (files) {
                    if (files.size > 0) {
                        file.type(files, fileTypeArray);
                    }
                }
            }

            var EventUtil = {
                addHandler: function (element, type, handler) {
                    if (element.addEventListener) {
                        element.addEventListener(type, handler, false);
                    } else if (element.attachEvent) {
                        element.attachEvent("on" + type, handler, false);
                    }
                },

                removeEventListener: function (element, type, handler) {
                    if (element.removeEventListener) {
                        element.removeEventListener(type, handler, false);
                    } else if (element.detachEvent) {
                        element.detachEvent("on" + type, handler, false);
                    }
                }
            }

            EventUtil.addHandler(dragElement, "drop", function (event) {
                event.preventDefault();
                event.stopPropagation();

                dropedFileReader(event).then((data) => {
                    for (let item of data) {
                        file.info(item);
                    }
                    _comparefile();
                });
            });

            EventUtil.addHandler(dragElement, "dragenter", function (event) {
                event.preventDefault();
                event.stopPropagation();
            });

            EventUtil.addHandler(dragElement, "dragover", function (event) {
                event.preventDefault();
                event.stopPropagation();
            });
        }

        //对比文件
        function _comparefile() {

            // filestate=0:默认状态 -1:忽略  1:有变动  2:配置需要上传 3远程没有，需要上传 
            if (_selectfilelist.length > 0) {
                var now = new Date();
                var timeoffset = now.getTimezoneOffset() * 60000;

                for (var k = 0; k < _selectfilelist.length; k++) {
                    var item = _selectfilelist[k];
                    item.filestate = 0;
                    //转换成utctime
                    item.utctime = item.lastModified + timeoffset;
                    //根据文件名称，获取各个段的文件夹
                    //拆分文件夹
                    var dirs = _builddirectory(item.fullPath);
                    if (dirs) {
                        // console.log(dirs);
                        if (dirs.length > 0) {
                            for (var dir of dirs) {
                                if (mapconfig.has(dir)) {
                                    var config = mapconfig.get(dir);
                                    if (!config.ignore) {
                                        item.filestate = 2;
                                    } else {
                                        item.filestate = -1;//忽略
                                    }
                                    break;
                                }
                            }
                        }
                    }

                    //上面监测多级文件夹
                    if (item.filestate == 0) {
                        //这里监测完整文件
                        if (mapconfig.has(item.fullPath)) {
                            var config = mapconfig.get(item.fullPath);
                            if (!config.ignore) {
                                item.filestate = 2;
                            }
                        } else {
                            if (mapremote.has(item.fullPath)) {
                                var one = mapremote.get(item.fullPath);
                                if (one.utctime < item.utctime) {
                                    item.filestate = 1;
                                }

                            } else {
                                //远程没有，本地有
                                item.filestate = 3;
                            }
                        }
                    }

                }
                _showtoui();
                //显示变动文件到UI
                // $(".uploadbtn").attr("disabeld", false);
            } else {
                _appendmessage("没有拖入文件");
            }
        }

        //生成多级目录
        function _builddirectory(full) {
            var newlist = new Array();
            var strs = full.split('/');
            strs.pop(); strs.shift();
            var temp = "/";
            for (var k = 0; k < strs.length; k++) {
                temp += strs[k] + "/";
                newlist.push(temp);
            }
            return newlist;
        }

        function _appendmessage(msg) {
            $(".pageheader").append("<span>" + (new Date()).Format("yyyy-MM-dd HH:mm:ss") + " " + msg + "</span>");
        }

        function _showtoui() {
            if (_selectfilelist.length > 0) {
                for (var k = 0; k < _selectfilelist.length; k++) {
                    var item = _selectfilelist[k];
                    if (item.filestate > 0) {
                        $(".dropcontext").find("ul").append("<li>" + _buildspan(item.filestate) + " " + item.fullPath + "</li>");
                    }
                }
            }
            setTimeout(function () {
                $(".uploadbtn").attr("disabled", false);
            }, 100);
        }

        function _buildspan(state) {
            switch (state) {
                case 1: return '<span class="update">变动</span>';
                case 2: return '<span class="need">必须</span>';
                case 3: return '<span class="defect">缺失</span>';
            }
        }


        //选择文件
        function funcselectfile(e) {
            for (var k = 0; k < (e).files.length; k++) {
                var fileitem = (e).files[k];
                if (_selectfilelist == null) { _selectfilelist = []; }
                _selectfilelist.push(fileitem);
            }
        }


        function btnupload() {
            uploadloadid = 0;
            // $(".uploadbtn").attr("disabeld", true);
            setTimeout(function () {
                $(".uploadbtn").attr("disabled", true);
            }, 100);
            _taketoupload();
        }


        var uploadloadid = 0;

        function _taketoupload() {

            if (uploadloadid == 0) {
                uploadloadid = layer.load();
            }

            if (_selectfilelist.length > 0) {

                var item = _selectfilelist.shift();
                if (item.filestate > 0) {
                    _uploaditem(item);
                } else {
                    _taketoupload();
                }

            } else {
                if (uploadloadid > 0) {
                    layer.close(uploadloadid);
                }
                _appendmessage("文件上传成功!");

                //更新版本
                // _apipost("/api/Home/SourceUpdate?projectid=" + sid, true, '', function (code, obj) {
                //     if (code == 200) {
                //         _appendmessage("项目版本升级成功");
                //     } else {
                //         _appendmessage("项目版本升级失败");
                //     }
                // });

            }

        }

        /**
         * 上传单个文件 
         */
        function _uploaditem(item) {
            if (item) {
                var fdata = new FormData();
                fdata.append("fullPath", item.fullPath);
                fdata.append("time", (new Date()).getTime());
                fdata.append("name", item.name);
                fdata.append(item.name, item);
                fdata.append("utctime", item.utctime);//转换成utctime
                fdata.append("lastModified", item.lastModified);//本地时间的time
                $.ajax({
                    url: "/api/spider/upload/drop?serviceid=" + sid + "&model=" + modelid,
                    type: 'post',
                    contentType: false,
                    processData: false,
                    async: true,
                    data: fdata,
                    headers: { "token": readToken() },
                    success: function (obj) {
                        console.log(obj);
                    },
                    error: function (res) {
                        console.error(res);
                    },
                    complete: function () {
                        _taketoupload();
                    }
                });
            }
        };

    </script>
</body>

</html>